package com.aptemo.webetek.client.widgets.userinfo;

import java.util.Date;
import java.util.MissingResourceException;

import com.aptemo.webetek.client.Webetek;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;

public class UserInfo
		extends Composite implements UserInfoPresenter.Display, ChangeHandler
{
	private static final String		QUERY_LOCALE	= "locale";

	private static UserInfoUiBinder	uiBinder		= GWT.create(UserInfoUiBinder.class);

	interface UserInfoUiBinder extends UiBinder<Widget, UserInfo>
	{
	}

	@UiField
	Label				emailField;

	@UiField
	Label				helloField;

	@UiField
	Anchor				loginField;

	@UiField
	Anchor				settingsField;

	private PopupPanel	settingsPanel	= new PopupPanel(true);
	private ListBox		langs			= new ListBox();

	private Timer		timer;

	private String	loginUrl;

	public UserInfo()
	{
		initWidget(uiBinder.createAndBindUi(this));

		// 
		timer = new Timer()
		{
			@Override
			public void run()
			{
				// read current date/time
				Date date = new Date();
				helloField.setText(DateTimeFormat.getFullDateFormat().format(date) + ", " + DateTimeFormat.getShortTimeFormat().format(date));
				timer.schedule(30 * 1000);
			}
		};
		timer.run();

		// settings panel
		FlexTable panel = new FlexTable();
		langs.addItem(Webetek.getConstants().english(), "en");
		langs.addItem(Webetek.getConstants().slovene(), "sl");
		langs.addChangeHandler(this);

		// set current language...
		String curLoc = LocaleInfo.getCurrentLocale().getLocaleName();
		for (int i = 0; i < langs.getItemCount(); i++)
		{
			if (langs.getValue(i).equals(curLoc))
			{
				langs.setSelectedIndex(i);
			}
		}

		panel.setWidget(1, 0, new Label(Webetek.getConstants().language()));
		panel.setWidget(1, 1, langs);
		settingsPanel.add(panel);
	}

	@Override
	public HasText getRole()
	{
		return helloField;
	}

	@Override
	public HasText getUserEmail()
	{
		return emailField;
	}

	@Override
	public HasText getSigninLink()
	{
		return loginField;
	}

	@Override
	public Widget getDisplay()
	{
		return this;
	}

	@Override
	public void setLoginTarget(String loginUrl)
	{
		this.loginUrl = loginUrl;
	}

	@UiHandler("settingsField")
	public void settingsClickHandler(ClickEvent event)
	{
		// Reposition the popup relative to the button
		Widget source = (Widget) event.getSource();
		int left = source.getAbsoluteLeft() - 100;
		int top = source.getAbsoluteTop() + 10;
		settingsPanel.setPopupPosition(left, top);
		settingsPanel.show();
	}

	@Override
	public void onChange(ChangeEvent event)
	{
		int index = langs.getSelectedIndex();

		setSelectedLanguage(langs.getValue(index));
	}
	
	@UiHandler("loginField")
	void onLoginClicked(ClickEvent event)
	{
		String url = loginUrl + Window.Location.getHash();
		loginField.setHref(url);
	}

	private boolean setSelectedLanguage(String locale)
	{
		if ((locale != null) && (!locale.isEmpty()))
		{

			String path = Window.Location.getPath();
			String query = Window.Location.getQueryString();
			if (!query.isEmpty())
			{
				// check for locale
				if (query.contains("locale="))
				{
					int i1 = query.indexOf("locale=");
					int i2 = query.indexOf("&", i1 + 1);
					if (i2 == -1)
					{
						i2 = query.length();
					}
					String tmp = query.substring(i1, i2);
					query = query.replaceAll(tmp, "");

				}
				else
				{
					query += "&";
				}
			}
			else
			{
				query += "?";
			}
			query += "locale=" + locale;

			// if english - don't touch...
			// if (locale.equals("en"))
			// {
			//
			// }
			// else
			// {
			Window.Location.replace(path + query + Window.Location.getHash());
			// }

			// save cookie
			Cookies.setCookie("language", locale);

			return true;
		}

		return false;
	}

	@Override
	public String translate(String key)
	{
		try
		{
			return Webetek.getConstants().getString(key);
		}
		catch (MissingResourceException e)
		{
			return key;
		}
	}
}
